package com.qiyuan.boot.web.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiyuan.boot.web.bean.Manager;
import com.qiyuan.boot.web.mapper.ManagerMapper;
import com.qiyuan.boot.web.service.ManagerService;
import com.qiyuan.boot.utils.BusinessException;
import com.qiyuan.boot.utils.ConstUtil;
import com.qiyuan.boot.utils.enums.DataStatusEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

/**
 * @author qiyuan
 */
@Service
@Transactional(rollbackFor=BusinessException.class)
public class ManagerServiceImpl  extends ServiceImpl<ManagerMapper, Manager> implements ManagerService {
    @Resource
    private ManagerMapper managerMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private JavaMailSender javaMailSender;

    @Override
    public Manager findByName(String username)throws BusinessException  {
        //通过用户名查询
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Manager::getUsername,username)
                .eq(Manager::getStatus,ConstUtil.DEFAULT_STATE);
        return  managerMapper.selectOne(queryWrapper);
    }

    /**
     * 注册用户
     * @param manager
     * @return
     * @throws BusinessException
     */
    @Override
    public Manager saveManager(Manager manager) throws BusinessException {
        try {
            if (manager.getId()==null){
                manager.setCreateTime(DateUtil.now());
            }
            //先验证邮箱是否已经被注册
            Manager byName = this.findByName(manager.getUsername());
            if (byName != null){
                throw new BusinessException("已经注册，不能再次注册。");
            }
            if(manager.getCode()!=null){
                String codes = (String) request.getSession().getAttribute("code");
                if (codes == null){
                    throw new BusinessException("验证码已经失效。");
                }

                int code = Integer.parseInt(codes);
                if(manager.getCode() != code){
                    throw new BusinessException("验证码输入错误。");
                }
            }
            //设置默认值
            manager.setHeadPic("https://qiyuan-1258470662.cos.ap-shanghai.myqcloud.com/qiyuan/image/touxiangwu.gif");
            manager.setBackground("https://qiyuan-1258470662.cos.ap-shanghai.myqcloud.com/qiyuan/image/350.jpg");
            manager.setPassword(SecureUtil.md5(manager.getPassword()));
            managerMapper.insert(manager);
            return manager;
        } catch (BusinessException e) {
            throw new BusinessException(e.getErrorMessage());
        }
    }

    /**
     * 修改密码
     * @param manager
     * @return
     * @throws BusinessException
     */
    @Override
    public Manager rePassword(Manager manager) throws BusinessException {
        try {
            //先验证邮箱是否已经被注册
            Manager byName = this.findByName(manager.getUsername());
            if (byName == null){
                throw new BusinessException("此邮箱还未注册！");
            }
            if(manager.getCode() != null){
                String codes = (String) request.getSession().getAttribute("code");
                if (codes == null){
                    throw new BusinessException("验证码已经失效。");
                }
                int code = Integer.parseInt(codes);
                if(manager.getCode() != code){
                    throw new BusinessException("验证码输入错误。");
                }
            }
            byName.setPassword(SecureUtil.md5(manager.getPassword()));
            byName.setUpdateTime(DateUtil.now());
            managerMapper.updateById(byName);
            return manager;
        } catch (BusinessException e) {
            throw new BusinessException(e.getErrorMessage());
        }
    }

    @Override
    public void sendOutEmail(String username,int type) throws BusinessException{
        try {
            //先验证邮箱是否已经被注册
            Manager byName = this.findByName(username);
            if (byName != null && 0 == type){
                throw new BusinessException("邮箱已经注册，不能再次注册。");
            }

            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("qiyuano@163.com");
            helper.setTo(username);
            if (1 == type){
                helper.setSubject("标题：奇缘网络找回密码");
            }else{
                helper.setSubject("标题：请收好您在奇缘网络的注册码");
            }

            String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
            HttpSession session = request.getSession();
            session.setAttribute("code", checkCode);
            String str;
            if (1 == type){
                str ="<h4>奇缘网络找回密码</h4>"+"<p style='color:#F00'>您的验证码为:"+checkCode+"</p>";
            }else{
                str ="<h4>欢迎您在奇缘注册</h4>"+"<p style='color:#F00'>您的验证码为:"+checkCode+"</p>";
            }
            //append("<p style='text-align:right'>右对齐</p>");
            helper.setText(str, true);

       /* FileSystemResource fileSystemResource=new FileSystemResource(new File("C:\\Users\\28937\\Desktop\\搞笑图片\\welcome.gif"));
        helper.addAttachment("啦啦啦",fileSystemResource);*/
            javaMailSender.send(message);
        } catch (BusinessException e) {
            throw new BusinessException(e.getErrorMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Manager> getManagerByPage(Manager manager) {
        Manager manager1 = (Manager) SecurityUtils.getSubject().getPrincipal();
        if (manager1.getType().equals(ConstUtil.SUPER_ADMIN)){
            manager.setType(ConstUtil.ADMIN);
        }
        if (manager1.getType().equals(ConstUtil.ADMIN)){
            manager.setType(ConstUtil.BOLG_MIN);
        }

        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(StringUtils.isNotBlank(manager.getUsername()),Manager::getUsername,manager.getUsername())
                             .like(StringUtils.isNotBlank(manager.getName()),Manager::getName,manager.getName())
                             .eq(StringUtils.isNotBlank(manager.getType()),Manager::getType,manager.getType())
                             .orderByDesc(Manager::getCreateTime)
                             .orderByDesc(Manager::getStatus);
        return managerMapper.selectList(queryWrapper);
    }

    @Override
    public void delManager(List<Integer> ids) throws BusinessException{
        try {
            managerMapper.deleteBatchIds(ids);
        }catch (BusinessException e){
            throw new BusinessException(e.getErrorMessage());
        }
    }

    @Override
    public void stopManager(List<Integer> ids, int key)throws BusinessException{
        try {
            List<Manager> managers = managerMapper.selectBatchIds(ids);
            if(managers.stream().anyMatch(x->x.getStatus()==key)){
                throw new BusinessException("已经是"+ DataStatusEnum.getValue(key)+"状态");
            }
            managers.forEach(x->x.setStatus(key));
            this.updateBatchById(managers);
        }catch (BusinessException e){
            throw new BusinessException(e.getErrorMessage());
        }
    }

    @Override
    public Manager updateManager(Manager manager) {
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(Manager::getId,manager.getId())
                             .eq(Manager::getUsername,manager.getUsername())
                             .eq(Manager::getStatus, ConstUtil.DEFAULT_STATE);

        if (managerMapper.selectCount(queryWrapper)>0){
             throw new BusinessException("用户名或者昵称已经存在");
        }

        if (manager.getPassword()!=null){
            manager.setPassword(SecureUtil.md5(manager.getPassword()));
        }

        managerMapper.updateById(manager);
        return manager;
    }

    /**
     * 查询默认设置
     * @return
     * @throws BusinessException
     */
    @Override
    public Manager defSteup() throws BusinessException {
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Manager::getId,2)
                .eq(Manager::getStatus,ConstUtil.DEFAULT_STATE);
        return  managerMapper.selectOne(queryWrapper);
    }

    /**
     * 修改个人信息
     * @return
     * @throws BusinessException
     */
    @Override
    public Manager updateManage(Manager manager) throws BusinessException {
        if (null == manager || null == manager.getId()){
            throw new BusinessException("请重新登录用户");
        }else{
            QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Manager::getId,manager.getId())
                    .ne(Manager::getId,1)
                    .ne(Manager::getId,2);
            Manager man = managerMapper.selectOne(queryWrapper);
            if (null != man){
                BeanUtils.copyProperties(manager,man);
                managerMapper.updateById(man);
                return man;
            }
        }
        return null;
    }

}
